#!python
# -*- coding: utf-8 -*-

from flask import Blueprint, request, render_template, url_for
import pymysql

from .db import get_db
from .admin import login_required

add_dev = Blueprint("add_dev", __name__)

@add_dev.route("/user/add", methods=["GET", "POST"])
@login_required
def add():
    if request.method == "GET":
        return render_template("add_devinfo.html")

    keys = ["username", "sn","email","phone","addr","qq","weixin","weibo"]

    d = {}
    for k in keys:
        v = request.form.get(k, "")
        d[k] = pymysql.escape_string(v)

    if not d["sn"]:
        return u"""设备序列号不能为空!<br><a href="javascript: window.history.back()">返回</a>"""
    conn = get_db()
    cur = conn.cursor()
    sql = "select id from devinfo where serial = '%s'" % d["sn"]
    cur.execute(sql)
    rs = cur.fetchall()
    if rs:
        cur.close()
        return u""" 设备序列号已存在!<br><a href="javascript: window.history.back()">返回</a>"""

    sql = u"""insert into devinfo (name, serial,email,phone,addr,qq,webchat,weibo)
    values('{username}', '{sn}', '{email}','{phone}','{addr}', '{qq}','{weixin}','{weibo}')""".format(**d)
    cur.execute(sql)
    conn.commit()
    cur.close()
    return u"""增加成功!<br><a href="%s">继续增加</a> """ % url_for(".add")
